package com.mrd.util;


import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Iterator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * 海关税号要素查询工具类
 *
 * @author luob
 */
public class HttpClientQPTool {

    // 查询必要参数
    private static String __VIEWSTATE;
    private static String __EVENTVALIDATION;


    /**
     * 查询方法入口
     *
     * @param goodsCode 10位完整税号
     * @return 要素，格式 :是否改良种用;:品种;:其他;
     */
    public static String getGoodsModeFromNetByJsoup(String goodsCode) throws Exception {
        // 过滤税号长度
        if (StringUtils.isEmpty(goodsCode) || goodsCode.length() != 10) {
            return "";
        }

        System.out.println("from www.nbedi.com:\t" + goodsCode);
        //init __VIEWSTATE and __EVENTVALIDATION
        initQueryProperties();
        // 调用具体的查询工具方法
        String resultString = getGoodsModeFromNetByJsoup(goodsCode, 1);
        System.out.println("result:\t" + resultString);
        return resultString;
    }

    /**
     * 初始化查询参数
     */
    private static void initQueryProperties() throws Exception {
        String urlStr = "http://www.nbedi.com/NBCPCAM/ClassifyQuery.aspx";
        Document doc = null;
        doc = Jsoup.connect(urlStr)
                //.data("__VIEWSTATE", "/wEPDwUKMTk3MDA5NDQ5NQ9kFgICAw9kFgQCBw8UKwALDxYIHghEYXRhS2V5cxYAHgtfIUl0ZW1Db3VudAIKHglQYWdlQ291bnQCAR4VXyFEYXRhU291cmNlSXRlbUNvdW50AgpkZGQWBB4IQ3NzQ2xhc3MFCGdyaWRIZWFkHgRfIVNCAgJkFgQfBAUKZ3JpZE9kZFJvdx8FAgIWBB8EBQtncmlkRXZlblJvdx8FAg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/np43nlKhkAgkPDxYGHghQYWdlU2l6ZQIKHg5DdXN0b21JbmZvVGV4dAU4PGZvbnQgY29sb3I9ImdyZWVuIj7kuIDlhbE2NTE5NuadoeiusOW9le+8jDEvNjUyMDwvZm9udD4eC1JlY29yZGNvdW50Aqz9A2RkGAEFHl9fQ29udHJvbHNSZXF1aXJlUG9zdEJhY2tLZXlfXxYBBQdpYlF1ZXJ5gA6B3RiQQesib4Hcz3/nn2moYRA=")
                //.data("__EVENTVALIDATION", "/wEWBAK6zLD2CQLTk4AnAuf5iaEJAurdxNgLF2S7eKC5TFejW180ukiaTSQh5qY=")
                //.data("ibQuery.x", ((int) (Math.random() * 10) + 30) + "")
                //.data("ibQuery.y", "" + ((int) (Math.random() * 5) + 5))
                .data("tbCodeTs", "9999999999").userAgent("Mozilla").timeout(3000).post();
        Element body = doc.body();
        Element __VIEWSTATE_obj = body.getElementById("__VIEWSTATE");
        __VIEWSTATE = __VIEWSTATE_obj.attr("value");
        Element __EVENTVALIDATION_obj = body.getElementById("__EVENTVALIDATION");
        __EVENTVALIDATION = __EVENTVALIDATION_obj.attr("value");
    }

    /**
     * jsoup工具查询方法
     *
     * @param targetPage 分页查询参数，当前查询页码
     */
    private static String getGoodsModeFromNetByJsoup(String goodsCode, int targetPage)
            throws Exception {
        String urlStr = "http://www.nbedi.com/NBCPCAM/ClassifyQuery.aspx";
        Document doc = null;
        // 判断查询当前页码
        if (targetPage == 1) {
            doc = Jsoup
                    .connect(urlStr)
                    .data("__VIEWSTATE", __VIEWSTATE)
                    .data("__EVENTVALIDATION", __EVENTVALIDATION)
                    .data("ibQuery.x", ((int) (Math.random() * 10) + 30) + "")
                    .data("ibQuery.y", "" + ((int) (Math.random() * 5) + 5))
                    .data("tbCodeTs", goodsCode).userAgent("Mozilla").timeout(3000).post();
        } else {
            doc = Jsoup
                    .connect(urlStr)
                    .data("__VIEWSTATE", __VIEWSTATE)
                    .data("__EVENTVALIDATION", __EVENTVALIDATION)
                    .data("__EVENTTARGET", "pagePagination")
                    .data("__EVENTARGUMENT", targetPage + "").data("tbCodeTs", goodsCode)
                    .userAgent("Mozilla").timeout(3000).post();
        }
        Element body = doc.body();
        // 获取页面税号要素
        Element tb = body.getElementById("gvData");
        Elements tds = tb.getElementsByTag("td");
        // System.out.println(tb);
        int count = 0;
        String resultString = "";
        for (Iterator<Element> itr = tds.iterator(); itr.hasNext(); ) {
            Element e = itr.next();
            if (count % 5 == 4 && count > 5) {
                // System.out.println(e.text());
                resultString += ":" + e.text().trim() + ";";
            }
            count++;
        }
        // 清除要素最后的空格字符，注意：不要修改replaceAll的参数，" "不是空格，资料关键字：super 160 space
        resultString = resultString.replaceAll(" ", "");
        // 获取查询结果的总页数rcount
        int rcount = getRecordPageCount(body);
        if (rcount > 1 && targetPage < rcount) {
            resultString += getGoodsModeFromNetByJsoup(goodsCode, targetPage + 1);
        }
        return resultString;
    }


    /**
     * 获取返回页面的总页数
     */
    private static int getRecordPageCount(Element body) {
        Element tbWrapper = body.getElementById("pagePagination");
        Elements tds = tbWrapper.getElementsMatchingText("一共");
        int count = 1;
        if (tds.size() > 0) {
            String presult = tds.get(0).text();
            String pageCountStr = presult.substring(presult.indexOf("/") + 1);
            try {
                count = Integer.parseInt(pageCountStr);
            } catch (Exception e) {
            }
        }
        return count;
    }

    /**
     * 旧版httpclient查询工具方法
     */
    public static String getGoodsModeFromNet(String goodsCode) throws Exception {
        DefaultHttpClient httpclient = new DefaultHttpClient();

        // 通关网查询地址
        String url = "http://www.hscode.net/IntegrateQueries/YsInfoPager?taxCode=" + goodsCode
                + "&ran=" + (int) (Math.random() * 10000 + 1);
        System.out.println(url);
        HttpGet httpGet = new HttpGet(url);
        HttpResponse response1 = httpclient.execute(httpGet);
        try {
            String result = "";
            // if(response1.getStatusLine().equals("HTTP/1.1 200 OK")) {
            HttpEntity entity1 = response1.getEntity();
            InputStream in = entity1.getContent();
            BufferedReader br = new BufferedReader(new InputStreamReader(in, "GBK"));
            String tempbf;
            StringBuffer html = new StringBuffer(100);
            while ((tempbf = br.readLine()) != null) {
                html.append(tempbf + "\n");
            }
            Pattern p = Pattern.compile("1:[^<]*;");
            Matcher m = p.matcher(html);
            if (m.find()) {
                result = m.group();
            }
            EntityUtils.consume(entity1);
            // }
            return result;
        } finally {
            httpGet.releaseConnection();
        }
    }

    public static void main(String[] args) {
        String result;
        try {
            //			result = getGoodsModeFromNet("2202100090");
            //			result = getGoodsModeFromNetByJsoup("8443399000");
            //8708409103
            // 2204210000 分页
            result = getGoodsModeFromNetByJsoup("2204210000");
            System.out.println(result);

            //initQueryProperties();
            //System.out.println(__VIEWSTATE+"\n"+__EVENTVALIDATION);
            // int jkg = (int) ' ';
            // int zkg = (int) ' ';
            // System.out.println("jkg:" + jkg + "\nzkg:" + zkg);
            //			System.out.println((int) (Math.random() * 10) + 30);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main1(String[] args) throws ClientProtocolException, IOException {
        DefaultHttpClient httpclient = new DefaultHttpClient();

        String url = "http://www.hscode.net/IntegrateQueries/QueryYS/?Tariff10CodeQuery=0103911010&ran="
                + (int) (Math.random() * 10000 + 1);
        System.out.println(url);
        HttpGet httpGet = new HttpGet(url);
        HttpResponse response1 = httpclient.execute(httpGet);

        // The underlying HTTP connection is still held by the response object
        // to allow the response content to be streamed directly from the network socket.
        // In order to ensure correct deallocation of system resources
        // the user MUST either fully consume the response content  or abort request
        // execution by calling HttpGet#releaseConnection().

        try {
            System.out.println(response1.getStatusLine());
            HttpEntity entity1 = response1.getEntity();
            // do something useful with the response body
            // and ensure it is fully consumed
            InputStream in = entity1.getContent();
            BufferedReader br = new BufferedReader(new InputStreamReader(in, "GBK"));
            String tempbf;
            StringBuffer html = new StringBuffer(100);
            while ((tempbf = br.readLine()) != null) {
                html.append(tempbf + "\n");
            }
            //	            System.out.println(html.toString());
            Pattern p = Pattern.compile("1:[^<]*;");
            Matcher m = p.matcher(html);
            if (m.find()) {
                System.out.println(m.group());
                String tStr = m.group();
                p = Pattern.compile(":[^;]*;");
                Matcher m2 = p.matcher(tStr);
                while (m2.find()) {
                    System.out.println(m2.group());
                }
            }
            EntityUtils.consume(entity1);
        } finally {
            httpGet.releaseConnection();
        }
    }
}
